package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.JsonObject;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import io.swagger.util.Json;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.bridge.Message;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Value("${sky.shop.address}")
    private String shopAddress;
    @Value("${sky.baidu.ak}")
    private String ak;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 用户下单
     * 先向订单表和订单明细表插入数据，再执行清空购物车
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //处理业务异常
        //1.地址簿是否为空
        AddressBook addressBook=addressBookMapper.getAddressBookById(ordersSubmitDTO.getAddressBookId());
        StringBuilder address=new StringBuilder();
        address.append(addressBook.getProvinceName());
        address.append(addressBook.getCityName());
        address.append(addressBook.getDistrictName());
        address.append(addressBook.getDetail());
        if(addressBook==null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        checkOutOfRange(address.toString());
        //2.购物车是否为空
        ShoppingCart shoppingCart=new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCarts=shoppingCartMapper.listShoppingCart(shoppingCart);
        if(shoppingCarts==null||shoppingCarts.isEmpty()){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //向表中插入数据
        Orders orders=new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis())); //使用系统当前时间戳作为订单号
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setAddress(address.toString());
        orderMapper.insert(orders);
        //将购物车中的数据转换为订单信息表：购物车表(与用户id关联)=>订单细节表(与订单id关联)
        List<OrderDetail> orderDetails=new ArrayList<>();
        for(ShoppingCart shoppingCart1:shoppingCarts){
            OrderDetail orderDetail=new OrderDetail();
            BeanUtils.copyProperties(shoppingCart1,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetails);
        //清空购物车
        shoppingCartMapper.delete(shoppingCart);
        //封装返回结果
        OrderSubmitVO orderSubmitVO=OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    /**
     * 发起微信支付
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 查询当前用户
        User user=userMapper.selectById(BaseContext.getCurrentId());
        Orders orders=orderMapper.selectByNumberAndUserId(ordersPaymentDTO.getOrderNumber(),BaseContext.getCurrentId());
        // 调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject=weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(),// 订单号
//                new BigDecimal(String.valueOf(orders.getAmount())), // 金额（元）
//                "sky-takeout-order", // 描述信息
//                user.getOpenid() // 用户openId
//        );
//        if(jsonObject.getString("code")!=null && jsonObject.getString("code").equals("ORDERPAID")){
//            throw new OrderBusinessException(MessageConstant.PAY_FAILED_ORDERPAID);
//        }
        JSONObject jsonObject=new JSONObject();    //由于缺少相关认证材料，避免调用微信支付接口
        jsonObject.put("code","ORDERPAID");     //附加已支付标签，避开微信支付回调
        OrderPaymentVO orderPaymentVO=jsonObject.toJavaObject(OrderPaymentVO.class);
        orderPaymentVO.setPackageStr(jsonObject.getString("package"));
        orders.setCheckoutTime(LocalDateTime.now());  //直接执行数据库更新操作
        orders.setPayStatus(Orders.PAID);
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orderMapper.update(orders);
        Map<String,Object> claims=new HashMap<>();
        claims.put("type",WebSocketServer.ORDER_ARRIVAL);
        claims.put("orderId",orders.getId());
        claims.put("content","订单号："+orders.getNumber());
        String json=JSON.toJSONString(claims);
        webSocketServer.sendToAllClient(json);
        return orderPaymentVO;
    }

    /**
     * 微信服务器回调支付成功接口后的操作
     * @param outTradeNo
     */
    @Override
    public void paySuccess(String outTradeNo) {
        // 查询订单
        Orders orders=orderMapper.selectByNumberAndUserId(outTradeNo,BaseContext.getCurrentId());
        // 更新订单相关状态
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setPayStatus(Orders.PAID);
        orders.setCheckoutTime(LocalDateTime.now());
        orderMapper.update(orders);
        // 向管理端推送消息：type orderId content
        Map<String,Object> claims=new HashMap<>();
        claims.put("type",WebSocketServer.ORDER_ARRIVAL);
        claims.put("orderId",orders.getId());
        claims.put("content","订单号："+orders.getNumber());
        String json=JSON.toJSONString(claims);
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 查询历史订单
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult queryHistory(int page, int pageSize, Integer status) {
        PageHelper.startPage(page,pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO=new OrdersPageQueryDTO();
        ordersPageQueryDTO.setStatus(status);
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        //先查询该用户的历史订单
        Page<Orders> ordersPage=orderMapper.pageQuery(ordersPageQueryDTO);
        List<OrderVO> orderVOS=new ArrayList<>();
        //再根据订单号查询订单细节封装成
        if(ordersPage!=null&&ordersPage.getTotal()>0){
            for(Orders orders:ordersPage){
                List<OrderDetail> orderDetails=orderDetailMapper.selectByOrderId(orders.getId());
                OrderVO orderVO=new OrderVO();
                BeanUtils.copyProperties(orders,orderVO);
                orderVO.setOrderDetailList(orderDetails);
                orderVOS.add(orderVO);
            }
        }
        return new PageResult(ordersPage.getTotal(),orderVOS);
    }

    /**
     * 查看订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO queryOrderDetail(Long id) {
        Orders orders=orderMapper.selectById(id);
        List<OrderDetail> orderDetails=orderDetailMapper.selectByOrderId(orders.getId());
        OrderVO orderVO=new OrderVO();
        //封装数据
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancelOrder(Long id) throws Exception {
        // 查询订单
        Orders orders= orderMapper.selectById(id);
        // 检查订单是否存在
        if(orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 订单状态>2，商家已接入，不能取消
        if(orders.getStatus()>2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 调用退款接口
        orderRefund(orders);
        // 更新订单状态
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     * 重新添加到购物车并返回
     * @param id
     */
    @Override
    public void repetition(Long id) {
        // 将订单对象转换为购物车对象（外键由order_id变更为user_id）
        List<OrderDetail> orderDetails=orderDetailMapper.selectByOrderId(id);
        List<ShoppingCart> shoppingCarts=orderDetails.stream().map(orderDetail->{
            ShoppingCart shoppingCart=new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart,"id");
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartMapper.insertBatch(shoppingCarts);
    }

    /**
     * 将Orders对象转换为OrderVO对象
     * @param orders
     * @return
     */
    private OrderVO Orders2OrderVO(Orders orders){
        OrderVO orderVO=new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        // 查询订单详细信息
        List<OrderDetail> orderDetails=orderDetailMapper.selectByOrderId(orders.getId());
        // 将菜品信息拼接为字符串
        List<String> orderDetailsStrings=orderDetails.stream().map(orderDetail -> {
            String orderDish=orderDetail.getName()+"*"+orderDetail.getNumber()+";";
            return orderDish;
        }).collect(Collectors.toList());
        orderVO.setOrderDetailList(orderDetails);
        orderVO.setOrderDishes(String.join("",orderDetailsStrings));
        return orderVO;
    }

    /**
     * 管理端搜索订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult searchOrder(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 分页查询order
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> ordersPage=orderMapper.pageQuery(ordersPageQueryDTO);
        List<Orders> ordersList=ordersPage.getResult();
        // 将order封装为orderVo
        List<OrderVO> orderVOS=ordersList.stream().map(this::Orders2OrderVO).collect(Collectors.toList());
        return new PageResult(ordersPage.getTotal(),orderVOS);
    }

    /**
     * 统计各订单状态
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO=new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(orderMapper.countByStatus(Orders.CONFIRMED));
        orderStatisticsVO.setToBeConfirmed(orderMapper.countByStatus(Orders.TO_BE_CONFIRMED));
        orderStatisticsVO.setDeliveryInProgress(orderMapper.countByStatus(Orders.DELIVERY_IN_PROGRESS));
        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders=Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 店铺拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejectOrder(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        // 查询订单信息
        Orders orders=orderMapper.selectById(ordersRejectionDTO.getId());
        // 订单存在且状态为2（待接单）才可退单
        if(orders==null || !orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 调用退款接口

        // 修改数据库中订单信息
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 执行订单退款操作
     * @param orders
     */
    private String orderRefund(Orders orders) throws Exception{
        String refundResult=null;
        // 支付状态为已支付
        if(orders.getPayStatus().equals(Orders.PAID)){
            // 调用微信退款接口
//            refundResult =weChatPayUtil.refund(
//                    orders.getNumber(),
//                    orders.getNumber(),
//                    new BigDecimal(String.valueOf(orders.getAmount())),
//                    new BigDecimal(String.valueOf(orders.getAmount()))
//            );
            // 修改支付状态
            orders.setPayStatus(Orders.REFUND);
        }
        log.info("退款结果：{}",refundResult);
        return refundResult;
    }
    /**
     * 店家取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void adminCancelOrder(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 获取订单
        Orders orders=orderMapper.selectById(ordersCancelDTO.getId());
        // 退款
        orderRefund(orders);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 店家派送订单
     * @param id
     */
    @Override
    public void deliveryOrder(Long id) {
        Orders orders=orderMapper.selectById(id);
        // 判断订单状态
        if(orders==null||!orders.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void completeOrder(Long id) {
        Orders orders=orderMapper.selectById(id);
        // 校验订单状态
        if(orders==null || !orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminderOrder(Long id) {
        Orders order=orderMapper.selectById(id);
        if(order==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map<String,Object> claims=new HashMap<>();
        claims.put("type", WebSocketServer.ORDER_URGE);
        claims.put("orderId",id);
        claims.put("content","订单号："+order.getNumber());
        String json=JSON.toJSONString(claims);
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 检验配送地址是否超出范围
     * @param address
     */
    private void checkOutOfRange(String address){
        Map<String,String> claims=new HashMap<>();
        claims.put("address",shopAddress);
        claims.put("output","json");
        claims.put("ak",ak);
        String baiduUrl="https://api.map.baidu.com/geocoding/v3";
        String baiduDirectionLite="https://api.map.baidu.com/directionlite/v1/driving";
        // 获取店铺经纬坐标
        String shopCoordinate= HttpClientUtil.doGet(baiduUrl,claims);
        JSONObject jsonObject=JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException(MessageConstant.LOCATION_RESOLUTION_FAILED);
        }
        // 数据解析
        JSONObject location=jsonObject.getJSONObject("result").getJSONObject("location");
        String lat=location.getString("lat");
        String lng=location.getString("lng");
        log.info("店铺经纬坐标：{}，{}",lat,lng);
        String shopLatLng=lat+","+lng;
        claims.put("address",address);
        // 获取用户地址经纬坐标
        String userCoordinate=HttpClientUtil.doGet(baiduUrl,claims);
        jsonObject=JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException(MessageConstant.LOCATION_RESOLUTION_FAILED);
        }
        location=jsonObject.getJSONObject("result").getJSONObject("location");
        lat=location.getString("lat");
        lng=location.getString("lng");
        log.info("用户经纬坐标：{}，{}",lat,lng);
        String userLatLng=lat+","+lng;
        claims.put("origin",shopLatLng);
        claims.put("destination",userLatLng);
        claims.put("steps_info","0");
        // 路线规划
        String json=HttpClientUtil.doGet(baiduDirectionLite,claims);
        jsonObject=JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException(MessageConstant.LOCATION_RESOLUTION_FAILED);
        }
        JSONObject result=jsonObject.getJSONObject("result");
        JSONArray jsonArray=(JSONArray) result.get("routes");
        Integer distance=(Integer) ((JSONObject) jsonArray.get(0)).get("distance");
        log.info("配送距离：{}",distance);
        if(distance>5000){
            // 超出配送距离
            throw new OrderBusinessException(MessageConstant.OUT_OF_DELIVERY_RANGE);
        }
    }
}
